﻿@page "/HtCtpList"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using HtERP.Data
@using Microsoft.AspNetCore.Components.QuickGrid
@using ClosedXML.Excel
@inject IJSRuntime JS
@attribute [Authorize]

<PageTitle>HtCtpList</PageTitle>

<div>
    <strong><font size="5" style="color:#016f5e">CTP制版</font></strong>
    <em>（共: <strong>@numResults() </strong>条，数量: <strong>@TotalQuantity() </strong>，价格: <strong>@Totalprice()</strong>元。）</em>
    每页显示条数:
    <select @bind="@pagination.ItemsPerPage">
        <option>50</option>
        <option>200</option>
        <option>500</option>
        <option>1000</option>
        <option>2000</option>
    </select>
    <button class="btn btn-primary" @onclick="DownloadExcel">下载Excel</button>
    <button class="btn btn-primary" @onclick="查询今天">今天</button>
    <button class="btn btn-primary" @onclick="查询昨天">昨天</button>
    <button class="btn btn-primary" @onclick="查询前天">前天</button>
    编号
    <input @bind="Text1" id="t1" type="number" style="width:110px; background-color:antiquewhite" />
    <button class="btn btn-primary" @onclick="按编号查询">按编号查询</button>

</div>

<div>
    <input @bind="date1" id="tt" type="date" style="width:120px" />
    <input @bind="date2" id="tt" type="date" style="width:120px" />
    <input type="search" autofocus @bind="nameFilter" placeholder="客户..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter1" placeholder="工作名..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter2" placeholder="CTP型号..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter3" placeholder="要求说明..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter4" placeholder="送货地点..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter5" placeholder="制作员..." style="width:120px" />
    <button class="btn btn-primary" @onclick="查询">查询</button>
    <button class="btn btn-primary" @onclick="清空搜索项">清空搜索项</button>
</div>


@if (ls == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <div>
        <QuickGrid Items="items" Theme="corporate" class="table" Pagination="@pagination">
       
            <PropertyColumn Property="@(c => c.编号)" Sortable="true" Align="Align.Right" Title="编号" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true" />
           
            <TemplateColumn Title="日期" SortBy="@日期排序" Align="Align.Center">
                    <input id="date1" type="date" @bind="@(context.输出日期)" style="width:98px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="客户" SortBy="@客户排序" Align="Align.Center">
                    <input type="text" @bind="@(context.客户)" @onclick="khLoadList" list="options" style="min-width:88px" @bind:after="@(() => 更新数据(context))">
                        <datalist id="options">
                        <option value="现金"></option>
                        <option value="临时"></option>
                        @if(kh!=null) foreach (var forecast in kh)
                            {
                                <option value="@forecast.客户ID"></option>
                            }
                            <!-- 更多选项 -->
                        </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="工作名" SortBy="@品名排序" Align="Align.Center" >
                    <input type="text" @bind=@(context.文件或工作名) style="min-width:168px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="长" Align="Align.Center">
                    <input  type="number" @bind="@(context.长)" style="text-align: right; width:40px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="宽"  Align="Align.Center">
                    <input  type="number" @bind="@(context.宽)" style="text-align: right; width:40px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="数量" SortBy="@张数排序" Align="Align.Center">
                    <input type="number" @bind="@(context.总色数)" style="text-align: right; width:48px" @bind:after="@(() => 计算CTP价格(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="要求" SortBy="@要求排序" Align="Align.Center">
                    <input type="text" @bind="@(context.输出要求)" style="min-width:158px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>

            <TemplateColumn Title="急" Align="Align.Center">
                <input id="Checkbox2" type="checkbox" @bind=@(context.急) style="width:18px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>

            <TemplateColumn Title="送货地点" SortBy="@送货排序" Align="Align.Center">
                    <input id="textsh" type="text" @bind="@(context.送货地点)" style=" min-width:66px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>

            <TemplateColumn Title="完成" SortBy="@rankSort" Align="Align.Center">
                <input id="Checkbox1" type="checkbox" @bind=@(context.已输出) style="width:28px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="板材型号" SortBy="@类型排序" Align="Align.Center" >
                    <input type="text" @bind="@(context.CTP板材型号)" @onclick="xhLoadList" list="zzoptions" style=" min-width:88px" @bind:after="@(() => 计算CTP价格(context))">
                <datalist id="zzoptions">
                    @if (xhlist != null) foreach (var forzz in xhlist)
                    {
                        <option value="@forzz.CTP板材型号ID"></option>
                    }
                </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="咬口" Align="Align.Center">
                    <input type="text" @bind="@(context.印刷机咬口要求)" @onclick="ykLoadList" list="ykoptions" style=" width:46px" @bind:after="@(() => 更新数据(context))">
                <datalist id="ykoptions">
                        @if (ykdxlist != null) foreach (var forzz in ykdxlist)
                    {
                            <option value="@forzz.印刷机咬口要求"></option>
                    }
                </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="方向" Align="Align.Center">
                    <input type="text" @bind="@(context.咬口方向)" list="fxoptions" style=" width:46px" @bind:after="@(() => 更新数据(context))">
                <datalist id="fxoptions">
                        <option value="上"></option>
                        <option value="下"></option>
                        <option value="左"></option>
                        <option value="右"></option>
                </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="网线" Align="Align.Center">
                    <input type="text" @bind="@(context.加网线数)" @onclick="wxLoadList" list="wxoptions" style=" width:50px" @bind:after="@(() => 更新数据(context))">
                <datalist id="wxoptions">
                        @if (wxlist != null) foreach (var forzz in wxlist)
                    {
                            <option value="@forzz.加网线数"></option>
                    }
                </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="网点" Align="Align.Center" >
                    <input type="text" @bind="@(context.网点类型)" @onclick="wdLoadList" list="wdoptions" style=" min-width:60px" @bind:after="@(() => 更新数据(context))">
                <datalist id="wdoptions">
                        @if (wdlist != null) foreach (var forzz in wdlist)
                    {
                            <option value="@forzz.网点类型"></option>
                    }
                </datalist>
            </TemplateColumn>
                
            <TemplateColumn Title="设计费" Align="Align.Center">
                    <input type="number" class="priceinput" 
                           style="text-align: right; width:58px"
                           value="@(context.设计制作费?.ToString("F2") ?? "NULL")"
                           @onchange="@(e => context.设计制作费 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                           @onblur="@(() => 合计CTP价格(context))"/>
            </TemplateColumn>
            
            <TemplateColumn Title="CTP费"  Align="Align.Center">
                    <input type="number" class="priceinput"
                           style="text-align: right; width:58px"
                           value="@(context.版费?.ToString("F2") ?? "NULL")"
                           @onchange="@(e => context.版费 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                           @onblur="@(() => 合计CTP价格(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="其他费用" Align="Align.Center">
                    <input type="number"  class="priceinput" 
                           style="text-align: right; width:58px"
                           value="@(context.其他费用?.ToString("F2") ?? "NULL")"
                           @onchange="@(e => context.其他费用 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                           @onblur="@(() => 合计CTP价格(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="价格" SortBy="@价格排序" Align="Align.Center">
                    <input type="number"  class="priceinput"
                           style="text-align: right; width:68px"
                           value="@(context.应收?.ToString("F2") ?? "NULL")"
                           @onchange="@(e => context.应收 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                           @onblur="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="结清" Align="Align.Center">
                <input id="Checkbox3" type="checkbox" @bind=@(context.结清) style="width:18px" disabled />
            </TemplateColumn>
            <TemplateColumn Title="制作员" SortBy="@制作排序" Align="Align.Center" >
                    <input type="text" @bind="@(context.制作员1)" @onclick="ygLoadList" list="ygoptions" style="width:68px" @bind:after="@(() => 更新数据(context))">
                <datalist id="ygoptions">
                        @if (yglist != null) foreach (var foryg in yglist)
                    {
                        <option value="@foryg.姓名"></option>
                    }
                </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="备注" SortBy="@备注排序" Align="Align.Center" >
                    <input id="Text1" type="text" @bind="@(context.备注)" style="min-width: 66px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="" Align="Align.Center" >
                        <button @onclick="@(() => ShowDeleteEvent(context))" style="color:red">删</button>
            </TemplateColumn>
    
        </QuickGrid>
         <Paginator State="@pagination" />
    <p> <button class="btn btn-primary" @onclick="新插一行">新建</button> </p>
    </div>
}

@if (ShowDelete)
{
        <div class="custom-dialog" @onclick:stopPropagation>
            <div class="dialog-content">
                <h3> 是否确定要删除：</h3>
                <h4> @aa</h4>
                <p><button class="dialog-button" @onclick="Deleteit">确定删除</button> <button class="dialog-button" @onclick="HideDeleteEvent">取消</button></p>
            </div>
        </div>
}


@code {
    PaginationState pagination = new PaginationState { ItemsPerPage = 200 };

    [CascadingParameter]
    private Task<AuthenticationState>? authenticationState { get; set; }

    AuthState? AuthState;

    string nameFilter = string.Empty;
    string nameFilter1 = string.Empty;
    string nameFilter2 = string.Empty;
    string nameFilter3 = string.Empty;
    string nameFilter4 = string.Empty;
    string nameFilter5 = string.Empty;

    GridSort<CTP制作输出表> rankSort = GridSort<CTP制作输出表>
    .ByDescending(x => x.已输出);

    GridSort<CTP制作输出表> 日期排序 = GridSort<CTP制作输出表>.ByAscending(x => x.输出日期);
    GridSort<CTP制作输出表> 客户排序 = GridSort<CTP制作输出表>.ByAscending(x => x.客户);
    GridSort<CTP制作输出表> 品名排序 = GridSort<CTP制作输出表>.ByAscending(x => x.文件或工作名);
    GridSort<CTP制作输出表> 类型排序 = GridSort<CTP制作输出表>.ByAscending(x => x.CTP板材型号);
    GridSort<CTP制作输出表> 张数排序 = GridSort<CTP制作输出表>.ByAscending(x => x.总色数);
    GridSort<CTP制作输出表> 价格排序 = GridSort<CTP制作输出表>.ByAscending(x => x.应收);
    GridSort<CTP制作输出表> 要求排序 = GridSort<CTP制作输出表>.ByAscending(x => x.输出要求);
    GridSort<CTP制作输出表> 送货排序 = GridSort<CTP制作输出表>.ByAscending(x => x.送货地点);
    GridSort<CTP制作输出表> 制作排序 = GridSort<CTP制作输出表>.ByAscending(x => x.制作员1);
    GridSort<CTP制作输出表> 备注排序 = GridSort<CTP制作输出表>.ByAscending(x => x.备注);


    private 客户[]? kh;
    private void khLoadList()
    {
        kh = HongtengDbCon.Db.Queryable<客户>().Where(it => it.IsDelete == false).ToArray();
    }

    public 员工[] yglist;
    private void ygLoadList()
    {
        yglist = HongtengDbCon.Db.Queryable<员工>().Where(it => it.是否已离职 != true).ToArray();
    }
    public CTP板材型号[] xhlist;
    private void xhLoadList()
    {
        xhlist = HongtengDbCon.Db.Queryable<CTP板材型号>().ToArray();
    }

    public CTP印刷机咬口要求[] ykdxlist;
    private void ykLoadList()
    {
        ykdxlist = HongtengDbCon.Db.Queryable<CTP印刷机咬口要求>().ToArray();
    }

    public CTP加网线数[] wxlist;
    private void wxLoadList()
    {
        wxlist = HongtengDbCon.Db.Queryable<CTP加网线数>().ToArray();
    }

    public CTP网点类型[] wdlist;
    private void wdLoadList()
    {
        wdlist = HongtengDbCon.Db.Queryable<CTP网点类型>().ToArray();
    }

    int? Text1 = null;
    DateTime date1 = DateTime.Now.AddDays(-1);
    DateTime date2 = DateTime.Now;
    string? customer = null;
    string? product = null;

    private CTP制作输出表[]? ls;
    private IQueryable<CTP制作输出表>? items;

    protected override async Task OnInitializedAsync()
    {
        AuthState = authenticationState?.Result as AuthState;
        ls = HongtengDbCon.Db.Queryable<CTP制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.Date).Where(it => it.IsDelete == false).ToArray();
        items = ls.AsQueryable();
        await InvokeAsync(StateHasChanged);
    }

    public int numResults()
    {
        int Count = items.Count();
        return Count;
    }
    public float? TotalQuantity()  //数量合计
    {
        float? total = items.Sum(item => item.总色数);
        return total;
    }
    public decimal? Totalprice()  //价格合计
    {
        decimal? total = items.Sum(item => item.应收);
        return total;
    }

    private void 查询今天()
    {
        ls = HongtengDbCon.Db.Queryable<CTP制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.Date).ToArray();
        items = ls.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 查询昨天()
    {
        ls = HongtengDbCon.Db.Queryable<CTP制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.AddDays(-1).Date).ToArray();
        items = ls.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 查询前天()
    {
        ls = HongtengDbCon.Db.Queryable<CTP制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.AddDays(-2).Date).ToArray();
        items = ls.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 按编号查询()
    {
        if (Text1>0)
        {
            ls = HongtengDbCon.Db.Queryable<CTP制作输出表>().Where(it => it.编号 == Text1).ToArray();
            items = ls.AsQueryable();
        }

    }

    private void 查询()
    {
        DateTime d1 = date1;
        DateTime d2 = date2;

        if (date2 < date1)
        {
            d1 = date2;
            d2 = date1;
        }


        ls = HongtengDbCon.Db.Queryable<CTP制作输出表>()
             .WhereIF(true, it => it.输出日期.Value.Date >= d1.Date && it.输出日期.Value.Date <= d2.Date)
             .WhereIF(!string.IsNullOrEmpty(nameFilter), it => it.客户.Contains(nameFilter))
             .WhereIF(!string.IsNullOrEmpty(nameFilter1), it => it.文件或工作名.Contains(nameFilter1))
             .WhereIF(!string.IsNullOrEmpty(nameFilter2), it => it.CTP板材型号.Contains(nameFilter2))
             .WhereIF(!string.IsNullOrEmpty(nameFilter3), it => it.输出要求.Contains(nameFilter3))
             .WhereIF(!string.IsNullOrEmpty(nameFilter4), it => it.送货地点.Contains(nameFilter4))
             .WhereIF(!string.IsNullOrEmpty(nameFilter5), it => it.制作员1.Contains(nameFilter5)).ToArray();

        items = ls.AsQueryable().Where(it => it.IsDelete == false);

    }


    private void 清空搜索项()
    {

        nameFilter = string.Empty;
        nameFilter1 = string.Empty;
        nameFilter2 = string.Empty;
        nameFilter3 = string.Empty;
        nameFilter4 = string.Empty;
        nameFilter5 = string.Empty;

    }
    private void 新插一行()
    {
        var ddd = HongtengDbCon.Db.Insertable(new CTP制作输出表() { 客户 = "", 输出日期 = DateTime.Now, 制作员1 = AuthState?.UserName, 总色数 = 0, 其他费用 = 0, 版费 = 0, 设计制作费 = 0, 应收=0,IsDelete = false }).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntity();
        var dda = ls.ToList();
        dda.Add(ddd);
        ls = dda.ToArray();
        items = ls.AsQueryable().Where(it => it.IsDelete == false);
        // pagination.SetCurrentPageIndexAsync(pagination.LastPageIndex ?? 1); //跳转到最后一页
    }

    private void 更新数据(CTP制作输出表 p)
    {
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }


    //弹出窗口-软删除一条
    string? aa;
    public CTP制作输出表? pp;
    public bool ShowDelete { get; set; }
    private void HideDeleteEvent()
    {
        ShowDelete = false;
    }
    private void ShowDeleteEvent(CTP制作输出表 p)
    {
        pp = p;
        aa = pp.编号+"，"+pp.客户 + "【" + pp.文件或工作名+"】";
        ShowDelete = true;
    }
    private void Deleteit()
    {
        pp.IsDelete = true;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(pp).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
        items = ls.AsQueryable().Where(it => it.IsDelete == false);
       
        ShowDelete = false;
    }

    public CTP制作输出表? ctp;
    private void 计算CTP价格(CTP制作输出表 ctp) //计算CTP价格
    {
        decimal dj = 0;
        if (HongtengDbCon.Db.Queryable<CTP板材型号>().Any(it => it.CTP板材型号ID == ctp.CTP板材型号))
        {
            dj = HongtengDbCon.Db.Queryable<CTP板材型号>().First(it => it.CTP板材型号ID == ctp.CTP板材型号).价格 ?? 25; //如果价格为null则取值25
        }
        else
        {
            dj = 25;
        }
        decimal ss = (decimal)(ctp.总色数 ?? 0.0f) ;
        ctp.版费 = ss * dj;
        ctp.应收 = ctp.其他费用 + ctp.版费 + ctp.设计制作费;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(ctp).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); //更新数据
    }
    private void 合计CTP价格(CTP制作输出表 ctp) //计算CTP价格
    {
        ctp.应收 = ctp.其他费用 + ctp.版费 + ctp.设计制作费;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(ctp).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); //更新数据
    }


    private async Task GoToPageAsync(int pageIndex) //跳转到指定分页
    {
        await pagination.SetCurrentPageIndexAsync(pageIndex);
    }

    public async Task DownloadExcel()
    {
        using (XLWorkbook workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet = workbook.AddWorksheet("Mysheet");

            worksheet.Cell(1, 1).Value = "完成";
            worksheet.Cell(1, 2).Value = "编号";
            worksheet.Cell(1, 3).Value = "日期";
            worksheet.Cell(1, 4).Value = "客户";
            worksheet.Cell(1, 5).Value = "工作名";
            worksheet.Cell(1, 6).Value = "数量";
            worksheet.Cell(1, 7).Value = "板材型号";
            worksheet.Cell(1, 8).Value = "价格";
            worksheet.Cell(1, 9).Value = "要求";
            worksheet.Cell(1, 10).Value = "送货地址";
            worksheet.Cell(1, 11).Value = "制作员";
            worksheet.Cell(1, 12).Value = "备注";

            worksheet.Row(1).Style.Font.Bold = true;


            int row = 2;
            foreach (var forzz in items)
            {
                worksheet.Cell(row, 1).Value = forzz.已输出.ToString();
                worksheet.Cell(row, 2).Value = forzz.编号.ToString();
                worksheet.Cell(row, 3).Value = forzz.输出日期;
                worksheet.Cell(row, 4).Value = forzz.客户;
                worksheet.Cell(row, 5).Value = forzz.文件或工作名;
                worksheet.Cell(row, 6).Value = forzz.总色数;
                worksheet.Cell(row, 7).Value = forzz.CTP板材型号;
                worksheet.Cell(row, 8).Value = forzz.应收;
                worksheet.Cell(row, 9).Value = forzz.输出要求;
                worksheet.Cell(row, 10).Value = forzz.送货地点;
                worksheet.Cell(row, 11).Value = forzz.制作员1;
                worksheet.Cell(row, 12).Value = forzz.备注;
                row++;
            }


            // 创建内存流用于保存工作簿
            using (var memoryStream = new MemoryStream())
            {
                // 将工作簿保存到内存流中
                workbook.SaveAs(memoryStream);

                // 重置内存流的位置，以确保从头开始读取
                memoryStream.Position = 0;

                // 这里可以将内存流进行进一步处理，例如发送为电子邮件附件或者作为API响应返回等
                var fileName = "CTP制版" + DateTime.Now.ToString()+".xlsx";

                using var streamRef = new DotNetStreamReference(stream: memoryStream);

                await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
            }
        }

    }


}
